define(['jquery'], function ($) {

    var Controller = {

        //下面是单个任务里面的变量
        curAiMsg: '',
        done: false,
        textStacks: [],
        writingText: "",
        writing: false,
        textOutputSi: 0,
        //上面是单个任务里面的变量

        lists: [],//保存所有引擎返回的结果
        ai_tasks: [],//当前任务队列
        task_timer: 0,//任务检测定时器
        doing_task: 0,//是否正在处理任务
        token: "",//AI接口需要的令牌
        ai_api: "",//AI接口地址
        ai_api_error: "",//AI接口提示的错误

        //初始化
        taskInit: function () {
            console.log("taskInit");
            Controller.done = false;
            Controller.textStacks = [];
            Controller.writingText = "";
            Controller.writing = false;
            if (Controller.textOutputSi) {
                clearInterval(Controller.textOutputSi)
            }
            Controller.textOutputSi = 0;
        },
        //开启AI单线程处理任务
        enterTask: function () {
            console.log("enterTask")
            if (Controller.doing_task == 0) {
                Controller.doing_task = 1;
                if (Controller.ai_tasks.length > 0) {
                    Controller.taskInit();

                    var task = Controller.ai_tasks.pop();
                    console.log("task", task);

                    $(".msg-sending-info").html("正在获取AI引擎: " + task.ai_name + " 的数据");
                    Controller.sendMessage(task);
                } else {
                    console.log("finish all task");
                    Controller.doing_task = 0;

                    clearInterval(Controller.task_timer);
                    Controller.task_timer = 0;

                    $(".msg-sending-info").html("所有AI引擎的数据都已获取完毕。");

                    if (Controller.ai_api_error) {
                        layer.msg(Controller.ai_api_error);
                        return false;
                    }
                    Controller.openAIResultWindow();

                }
            }
        },
        //打开AI结果窗口
        openAIResultWindow: function () {
            var postUrl = "/index/ai/ai_result";
            const formData = new FormData();

            for (var i = 0; i < Controller.lists.length; i++) {
                var item = Controller.lists[i];
                formData.append('ai[' + i + ']', item.ai);
                formData.append('ai_name[' + i + ']', item.ai_name);
                formData.append('message[' + i + ']', item.message);
            }

            console.log("data", formData);

            $.ajax({
                url: postUrl,
                type: 'post',
                data: formData,
                processData: false,
                contentType: false,
                async: false,
            }).done(function (res) {
                console.log("done", res);
                layer.open({
                    type: 1,
                    title: '小蛮妖为您呈现结果', // 设置标题
                    content: res,
                    shadeClose: false,
                    shade: [0.1, '#393D49'],
                    offset: 'rb',
                    area: ['20%', '80%'],
                    maxmin: false,
                });
            }).fail(function (res) {
                console.log("fail", res);
            });
        },

        //发送消息
        sendMessage: async function (task) {
            try {

                var pre_text = task.pre_text;
                var message = task.message;
                var ai = task.ai;
                var ai_name = task.ai_name;
                var role_id = task.role_id;
                var prompt_id = task.prompt_id;

                const formData = new FormData();
                if (pre_text != "") {
                    formData.append('message', pre_text + "\n" + message);
                } else {
                    formData.append('message', message);
                }
                formData.append('ai', ai);
                formData.append('role_id', role_id);
                formData.append('prompt_id', prompt_id);
                formData.append('site_x', 'gsq4');
                formData.append('token_x', Controller.token);

                var url = Controller.ai_api + "chat/sendText";

                // fetchCtrl = new AbortController()
                const response = await fetch(url, {
                    method: 'POST',
                    body: formData,
                    // signal: fetchCtrl.signal
                })

                if (!response.ok) {
                    Controller.doing_task = false;
                    return
                }
                const reader = response.body.getReader()
                const decoder = new TextDecoder('utf-8')

                Controller.textOutputSi = setInterval(() => {
                    console.log("enter textOutputSi setInterval");
                    if (Controller.writing) {
                        if (Controller.textStacks.length > 0) {
                            Controller.writingText += Controller.textStacks.shift()
                        }
                    } else {
                        if (Controller.textStacks.length > 0) {
                            Controller.writingText += Controller.textStacks.join('')
                            Controller.textStacks = []
                        }
                        clearInterval(Controller.textOutputSi)
                        Controller.textOutputSi = 0
                        if (Controller.writingText) {
                            Controller.lists.push({
                                "ai": ai,
                                "ai_name": ai_name,
                                "message": Controller.writingText
                            })
                            console.log("lists", Controller.lists);
                            $(".msg-sending-info").html("AI引擎: " + task.ai_name + "，数据获取完成。");
                            Controller.doing_task = 0;
                        }
                        Controller.writingText = '';
                    }
                }, 25)

                Controller.done = false;
                while (!Controller.done) {
                    const { value, done: readerDone } = await reader.read()
                    if (value) {
                        let char = decoder.decode(value)
                        if (char === '\n' && Controller.curAiMsg.endsWith('\n')) {
                            continue
                        }
                        if (char) {
                            if (char.indexOf('[error]') !== -1) {
                                Controller.writing = false
                                const error = char.replace('[error]', '')
                                console.log("error", error);
                                Controller.ai_api_error += error;
                                Controller.doing_task = 0;
                                break
                            }
                            Controller.writing = true
                            for (var i = 0; i < char.length; i++) {
                                Controller.textStacks.push(char[i])
                            }
                        }
                    }
                    Controller.done = readerDone
                }
                Controller.writing = false;
            } catch (e) {
                e = e.toString()
                if (e.indexOf('user aborted') !== -1) {
                    console.log('已终止连接')
                } else {
                    Controller.ai_api_error = e;
                    console.log('Request Error', e)
                }
                Controller.doing_task = false;
            }
        },

    };
    return Controller;
});
